package com.bhp.bhphrserver.security;

import com.bhp.bhphrserver.ctl.vo.RespBean;
import com.bhp.bhphrserver.entity.Hr;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName SecurityConfig
 * @Description TODO
 * @Author 包海鹏
 * @Date 2020/4/11 15:20
 * @Version 1.0
 * 开启基于注解的安全配直，启用＠PreAuthorize和＠PostAuthorize 两个注解。
 **/
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class BhpSecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private UserService userService;
    @Autowired
    private BhpAccessDeniedHandler bhpAccessDeniedHandler;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userService)
                // 加密方式，默认10次迭代
                .passwordEncoder(new BCryptPasswordEncoder());
    }

    /**
     * 注入自定义资源拦截器 & 自定义授权管理器
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {

                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O o) {
                        o.setSecurityMetadataSource(bfisms());
                        o.setAccessDecisionManager(badm());
                        return o;
                    }
                })
                .and()
                .formLogin()
//                .loginPage("/login_p")
                .loginProcessingUrl("/login")
                .usernameParameter("username")
                .passwordParameter("password")
                .failureHandler((request, response, e) -> {

                    response.setContentType("application/json;charset=UTF-8");
                    String msg = "登录失败";
                    if (e instanceof BadCredentialsException || e instanceof UsernameNotFoundException) {
                        msg = "账户名或者密码输入错误！";
                    } else if (e instanceof LockedException) {
                        msg = "账户被锁定，请联系管理员！";
                    } else if (e instanceof CredentialsExpiredException) {
                        msg = "密码过期，请联系管理员！";
                    } else if (e instanceof AccountExpiredException) {
                        msg = "账户过期，请联系管理员！";
                    } else if (e instanceof DisabledException) {
                        msg = "账户被禁用，请联系管理员！";
                    }

                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    ObjectMapper om = new ObjectMapper();
                    PrintWriter out = response.getWriter();
                    out.write(om.writeValueAsString(RespBean.error(msg)));
                    out.flush();
                    out.close();
                })
                .successHandler((request, response, authentication) -> {

                    response.setContentType("application/json;charset=UTF-8");
                    Hr hr = (Hr) authentication.getPrincipal();
                    ObjectMapper om = new ObjectMapper();
                    PrintWriter out = response.getWriter();
                    out.write(om.writeValueAsString(RespBean.ok("登录成功！", hr)));
                    out.flush();
                    out.close();
                })
                .permitAll()
                .and()
                .logout().permitAll()
                .and().csrf().disable()
                .exceptionHandling().accessDeniedHandler(bhpAccessDeniedHandler);
    }

    /**
     * 自定义资源拦截器实例
     *
     * @return
     */
    @Bean
    BhpFilterInvocationSecurityMetadataSource bfisms() {
        return new BhpFilterInvocationSecurityMetadataSource();
    }

    /**
     * 自定义授权管理器实例
     *
     * @return
     */
    @Bean
    BhpAccessDecisionManager badm() {
        return new BhpAccessDecisionManager();
    }

}
